package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.AliPayerAgentDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.tran.AliPayerAgent;
import com.framework.exception.RRException;
import com.framework.service.AgentService;
import com.framework.service.AliPayerAgentService;
import com.framework.validator.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("aliPayerAgentService")
public class AliPayerAgentServiceImpl extends ServiceImpl<AliPayerAgentDao, AliPayerAgent> implements AliPayerAgentService {

    @Autowired
    private AgentService agentService;

    @Override
    public AliPayerAgent queryAliAccount(String token) {
        SysAgent agent = agentService.queryAgentByToken(token);
        AliPayerAgent a=new AliPayerAgent();
        a.setAgentId(agent.getAgentId());
        AliPayerAgent aliPayerAgent = baseMapper.selectOne(a);
        if(aliPayerAgent==null){
            throw new RRException("9000","请绑定您的支付宝账号");
        }
        return aliPayerAgent;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void bindAliAccount(String token, String name, String aliAccount) {
        Assert.isBlank(name,"姓名不能为空");
        Assert.isBlank(aliAccount,"支付宝账号不能为空");
        SysAgent agent = agentService.queryAgentByToken(token);
        //不能根据缓存判断
        SysAgent sysAgent=agentService.queryAgentById(agent.getAgentId());
        System.out.println(agent.getRealName());
        if("未认证".equals(sysAgent.getRealName()) || "0".equals(sysAgent.getRealName())){
            throw  new RRException("9000","请进行实名认证");
        }
        if(!sysAgent.getName().equals(name)){
            throw  new RRException("9000","输入姓名不符合,请输入您的正确姓名");
        }
        AliPayerAgent a=new AliPayerAgent();
        a.setAliAccount(aliAccount);
        a.setAgentId(agent.getAgentId());
        a.setName(name);
        this.insertAliAccount(a);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAliAccount(String token, String name, String aliAccount) {
        Assert.isBlank(name,"姓名不能为空");
        Assert.isBlank(aliAccount,"支付宝账号不能为空");
        AliPayerAgent aliPayerAgent = this.queryAliAccount(token);
        if(aliPayerAgent==null){
            throw  new RRException("9000","未查询到支付宝账号,请绑定您的支付宝账号");
        }
        aliPayerAgent.setName(name);
        aliPayerAgent.setAliAccount(aliAccount);
        baseMapper.updateAliAccount(aliPayerAgent);
    }

    @Override
    public void insertAliAccount(AliPayerAgent aliPayerAgent) {
        AliPayerAgent a = baseMapper.selectOne(aliPayerAgent);
        if(a!=null){
            throw  new RRException("9000","已有支付宝账号，请勿重复添加");
        }
        baseMapper.insert(aliPayerAgent);
    }


}
